<template>
  <div class="login-container">
    <el-card class="box-card">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        auto-complete="on"
        label-position="left"
      >
        <div style="width: 40px; margin: 0 auto">
          <h3 style="align-content: center">FStart</h3>
        </div>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="12"
              ><el-checkbox v-model="checked">记住密码</el-checkbox></el-col
            >
            <el-col :span="12"
              ><el-button
                type="text"
                style="float: right"
                @click="dialogVisible = true"
                >忘记密码</el-button
              ></el-col
            >
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 49%"
            @click.native.prevent="handleLogin"
            :loading="loading"
            >登录</el-button
          >
          <el-button
            style="width: 49%; margin-left: 2%"
            @click="$router.push('/register')"
            >立即注册</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      title="忘记密码"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      width="60%"
    >
      <el-form
        ref="emailFormRef"
        :rules="rules"
        :model="emailForm"
        label-width="80px"
        v-if="active == 0"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="emailForm.code"> </el-input
            ></el-col>
            <el-col :span="8">
              <el-button
                :loading="codeLoading"
                :disabled="isDisable"
                size="small"
                round
                @click="sendMsg"
                >发送验证码</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              {{ statusMsg }}
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <el-form
        ref="userDataRef"
        :rules="rules"
        :model="userData"
        label-width="80px"
        v-if="active == 1"
      >
        <el-form-item label="新密码" prop="password">
          <el-row>
            <el-col :span="20">
              <el-input type="password" v-model="userData.password"> </el-input
            ></el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPassword">
          <el-row>
            <el-col :span="20">
              <el-input type="password" v-model="userData.checkPassword">
              </el-input
            ></el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <el-steps :active="active" finish-status="success">
        <el-step title="身份验证"> </el-step>
        <el-step title="修改密码"></el-step>
      </el-steps>

      <el-button style="margin-top: 12px" @click="next">下一步</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import userApi from "@/api/userManage";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不能小于6位"));
      } else {
        callback();
        // w;
      }
    };
    var validateEmail = (rule, value, callback) => {
      var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

      if (value === "" || value === undefined) {
        callback(new Error("请输入邮箱"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的邮箱验证规则,例如(xxx@aliyun.com)"));
      } else {
        callback();
      }
    };

    var validatePass = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error("密码长度不能小于6位或超过20位"));
      } else {
        if (this.userData.checkPassword !== "") {
          this.$refs.userDataRef.validateField("checkPassword");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.userData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,

      // 验证码
      statusMsg: "",

      // 是否勾选记住我复选框
      checked: false,

      // 忘记密码对话框
      dialogVisible: false,

      // emailForm
      emailForm: {},

      // 修改密码
      userData: {},
      // 步骤
      active: 0,

      rules: {
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
      },
    };
  },
  mounted() {
    const Base64 = require("js-base64").Base64;
    let username = localStorage.getItem("xxxx");
    if (username) {
      this.loginForm.username = Base64.decode(localStorage.getItem("xxxx"));
      this.loginForm.password = Base64.decode(localStorage.getItem("yyyy"));
      this.checked = true;
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.active = 0;
          this.userData = {};
          this.$refs["emailFormRef"].resetFields();
          done();
        })
        .catch((_) => {});
    },
    // 发送验证码
    sendMsg: function () {
      const self = this;

      let timerid;
      if (timerid) {
        return false;
      }
      self.statusMsg = "";

      // 向后台API验证码发送

      this.$refs["emailFormRef"].validate((valid) => {
        if (valid) {
          self.codeLoading = true;

          self.statusMsg = "验证码发送中...";

          let data = {
            email: self.emailForm.email,
            message: "FStart:忘记密码",
          };

          userApi
            .getEmailCode(data)
            .then((res) => {
              this.$message({
                showClose: true,
                message: "发送成功，验证码有效期5分钟",
                type: "success",
              });
              let count = 60;
              self.emailForm.code = "";
              self.codeLoading = false;
              self.isDisable = true;
              self.statusMsg = `验证码已发送,${count--}秒后重新发送`;
              timerid = window.setInterval(function () {
                self.statusMsg = `验证码已发送,${count--}秒后重新发送`;
                if (count <= 0) {
                  window.clearInterval(timerid);
                  self.isDisable = false;
                  self.statusMsg = "";
                }
              }, 1000);
            })
            .catch((err) => {
              console.log(err.response);
              this.isDisable = false;
              this.statusMsg = "";
              this.codeLoading = false;
              console.log(err.response.data.message);
            });
        } else {
          this.$message({
            message: "请输入正确的信息哦！",
            type: "warning",
          });
          return false;
        }
      });
    },

    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    handleLogin() {
      const Base64 = require("js-base64").Base64;

      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
              this.loading = false;
              /* ------ 账号密码的存储 ------ */
              console.log(this.checked);
              if (this.checked) {
                let password = Base64.encode(this.loginForm.password); // base64加密
                let username = Base64.encode(this.loginForm.username);
                localStorage.setItem("xxxx", username);
                localStorage.setItem("yyyy", password);
              } else {
                localStorage.removeItem("xxxx");
                localStorage.removeItem("yyyy");
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.$message.error("用户名或密码输入有误~");
          return false;
        }
      });
    },

    next() {
      if (this.active == 0) {
        // 向后台API验证码发送

        this.$refs["emailFormRef"].validate((valid) => {
          if (valid) {
            userApi.checkCodeIsOk(this.emailForm).then((resp) => {
              this.active = 1;
            });
          } else {
            this.$message({
              message: "请输入正确的信息哦！",
              type: "warning",
            });
            return false;
          }
        });
      } else if (this.active == 1) {
        this.forgetPassword();
      }
    },
    // 忘记密码
    forgetPassword() {
      let data = {
        password: this.userData.password,
        email: this.emailForm.email,
        code: this.emailForm.code,
      };

      this.$refs["userDataRef"].validate((valid) => {
        if (valid) {
          userApi.updatePasswordByEmailCode(data).then((resp) => {
            this.active = 0;
            this.$message({
              type: "success",
              message: resp.message,
            });
            // 清空数据
            (this.userData = {}), (this.emailForm = {});
            this.dialogVisible = false;
          });
        } else {
          this.$message({
            message: "请输入正确的信息哦！",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;

  overflow: hidden;

  display: flex;
  align-items: center;
}
.box-card {
  width: 450px;
  margin: 0 auto;
  /* margin-top: 9%; */
  overflow: hidden;
}
</style>
